package com.sayice.coursetable.logic.worker;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.os.Build;

import androidx.annotation.NonNull;
import androidx.core.app.NotificationCompat;
import androidx.work.Worker;
import androidx.work.WorkerParameters;

import com.sayice.coursetable.CourseTableApp;
import com.sayice.coursetable.R;
import com.sayice.coursetable.logic.Repository;
import com.sayice.coursetable.logic.dao.PreferencesDao;
import com.sayice.coursetable.logic.model.Exam;

import java.util.List;

/**
 * 考试安排监控任务
 */
public class ExamMonitorWorker extends Worker {
    public ExamMonitorWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
        super(context, workerParams);
    }

    @NonNull
    @Override
    public Result doWork() {
        List<Exam> exams = Repository.getExams(PreferencesDao.getUsername(),
                PreferencesDao.getPassword());
        if (exams != null) {
            int count = exams.size();
            if (count > PreferencesDao.getExamCount()) {
//            if (count >= PreferencesDao.getExamCount()) { // test
                // 创建通知渠道
                NotificationManager manager = (NotificationManager) CourseTableApp.context.getSystemService(
                        Context.NOTIFICATION_SERVICE);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    NotificationChannel channel = new NotificationChannel("normal",
                            "普通通知", NotificationManager.IMPORTANCE_DEFAULT);
                    manager.createNotificationChannel(channel);
                }
                // 推送通知
                Notification notification = new NotificationCompat.Builder(CourseTableApp.context, "normal")
                        .setContentTitle("考试安排有更新啦！")
                        .setSmallIcon(R.drawable.small_icon)
                        .build();
                manager.notify(1, notification);
                PreferencesDao.saveExamCount(count);
            }
        }
        return Result.success();
    }
}
